<?php

declare(strict_types=1);

namespace App\CustHub\Mapper;

use App\CustHub\Constants\RoomTaskCenterStatusConstants;
use App\CustHub\Constants\RoomTaskCenterTypeConstants;
use App\CustHub\Model\ChRoomTaskCenter;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Model;
use Mine\Abstracts\AbstractMapper;
use Mine\MineModel;
use function Hyperf\Collection\data_get;

class ChRoomTaskCenterMapper extends AbstractMapper
{
    public function assignModel()
    {
        $this->model = ChRoomTaskCenter::class;
    }

    public function listPage(array $params): array
    {
        $pageSize = $params['page_size'] ?? MineModel::PAGE_SIZE;
        $type = data_get($params, 'type');
        $status = data_get($params, 'status');
        $startTime = data_get($params, 'start_time');
        $endTime = data_get($params, 'end_time');

        $data = $this->model::query()
            ->selectRaw('id, type, status, total_count, success_count, fail_count, operator, created_at')
            ->where('uid', $params['uid'])
            ->when(filled($type), function ($query) use ($type) {
                $query->where('type', $type);
            })
            ->when(filled($status), function ($query) use ($status) {
                $query->where('status', $status);
            })
            ->when(!empty($startTime) && !empty($endTime), function ($query) use ($startTime, $endTime) {
                $query->whereBetween('created_at', [$startTime, $endTime]);
            })
            ->orderBy('created_at', 'desc')
            ->paginate((int)$pageSize);

        $data->getCollection()->transform(function ($item) {
           $item->type_text = RoomTaskCenterTypeConstants::getMessage($item->type);
           $item->status_text = RoomTaskCenterStatusConstants::getMessage($item->status);
           return $item;
        });

        return $this->setPaginate($data);
    }

    /**
     * 根据ID查询数据
     * @param int $id
     * @return ChRoomTaskCenter|Model|string|Builder|null
     */
    public function findById(int $id): ChRoomTaskCenter|Model|string|Builder|null
    {
        return $this->model::query()->where('id', $id)->first();
    }
}